package com.runnor.common.websys.system.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runnor.common.websys.system.entity.ApiResult;
import com.runnor.common.websys.system.entity.Article;
import com.runnor.common.websys.system.entity.Sysdict;
import com.runnor.common.websys.system.entity.bo.ArticleBo;
import com.runnor.common.websys.system.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("api/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('article:list')")
    public ResponseEntity page(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "10") Integer size,
                               ArticleBo article) {

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.like(StringUtils.hasText(article.getTitle()), "title", article.getTitle())
                .eq(StringUtils.hasText(article.getCategory()), "category", article.getCategory())
                .like(StringUtils.hasText(article.getAccountName()), "account_name", article.getAccountName())
                .eq(article.getIstop() != null, "istop", article.getIstop())
                .like(StringUtils.hasText(article.getKeyword()), "keyword", article.getKeyword())
        ;

        if (StringUtils.hasText(article.getState())) {
            switch (article.getState()) {
                //已发布
                case "1":
                    queryWrapper.eq("audit_state", 1);
                    queryWrapper.eq("article_state", 1);
                    queryWrapper.ltSql("issue_time", "now()");
                    break;
                //待发布
                case "0":
                    queryWrapper.eq("audit_state", 1);
                    queryWrapper.eq("article_state", 1);
                    queryWrapper.geSql("issue_time", "now()");
                    break;
                //待审核
                case "-1":
                    queryWrapper.eq("article_state", 0);
                    queryWrapper.and(
                            q -> {
                                ((QueryWrapper) q).eq("article_state", 0);
                                ((QueryWrapper) q).or();
                                ((QueryWrapper) q).isNull("audit_state");
                            }
                    );
                    break;
                //审核驳回
                case "-2":
                    queryWrapper.eq("audit_state", 0);
                    break;
            }
        }

        if (article.getDate() != null) {
            List<String> list = Arrays.asList(article.getDate());
            queryWrapper.between("date(issue_time)", list.get(0), list.get(1));
        }

        queryWrapper.eq("deleted", 0);

        queryWrapper.orderByDesc("edit_time");
        queryWrapper.orderByDesc("issue_time");

        Page data = articleService.pages(new Page(current, size), queryWrapper);

        return ResponseEntity.ok(ApiResult.ok(data));
    }

    /**
     * 根据code查询字典
     */
    @GetMapping("/getById")
    public ResponseEntity getById(String no) {
        Article article = articleService.getById(no);
        return ResponseEntity.ok(ApiResult.ok(article));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('article:add')")
    public ResponseEntity save(Article article) {
        article.setArticleState(1);
        boolean save = articleService.save(article);
        return ResponseEntity.ok(ApiResult.ok(save));
    }

    /**
     * 修改
     */
    @PostMapping("/updateById")
    @PreAuthorize("hasAuthority('article:edit')")
    public ResponseEntity updateById(Article article) {
        //当前文章状态 发布状态 直接修改
        if (article.getArticleState() == 1) {
            boolean save = articleService.updateById(article);
            return ResponseEntity.ok(ApiResult.ok(save));
            //当前文章状态  暂存状态  需要修改状态
        } else if (article.getArticleState() == 0) {

            //情况1   发布 状态下  点击  暂存
            if (StringUtils.hasText(article.getEditNo())) {

                article.setArticleState(1);

                UpdateWrapper updateWrapper = new UpdateWrapper();

                updateWrapper.eq("no", article.getEditNo());

                updateWrapper.set("title", article.getTitle());
                updateWrapper.set("content", article.getContent());
                updateWrapper.set("category", article.getCategory());
                updateWrapper.set("picture", article.getCategory());
                updateWrapper.set("istop", article.getIstop());
                updateWrapper.set("keyword", article.getKeyword());
                updateWrapper.set("source", article.getSource());
                updateWrapper.set("link", article.getLink());
                updateWrapper.set("audit_state", article.getAuditState());
                updateWrapper.set("audit_describe", article.getAuditDescribe());
                updateWrapper.set("issue_time", article.getIssueTime());

                boolean update = articleService.update(null, updateWrapper);

                boolean remove = articleService.removeById(article.getNo());

                Article updateArticle = articleService.getById(article.getEditNo());

                return ResponseEntity.ok(ApiResult.ok(updateArticle));

                //情况二 新增 点击的暂存  再点击 发布
            } else {

                article.setArticleState(1);

                boolean save = articleService.updateById(article);
                return ResponseEntity.ok(ApiResult.ok(save));
            }
        }

        return ResponseEntity.ok(ApiResult.ok(null));
    }

    /**
     * 删除
     */
    @GetMapping("/deletes")
    @PreAuthorize("hasAuthority('article:del')")
    public ResponseEntity deletes(String nos) {
        boolean b = articleService.removeBatchByIds(Arrays.asList(nos.split(",")));
        return ResponseEntity.ok(ApiResult.ok(b));
    }

    /**
     * 删除
     */
    @GetMapping("/removeById")
    @PreAuthorize("hasAuthority('article:del')")
    public ResponseEntity removeById(String no) {
        boolean b = articleService.removeById(no);
        return ResponseEntity.ok(ApiResult.ok(b));
    }

    /**
     * 暂存
     */
    @PostMapping("/articleZanCunById")
    @PreAuthorize("hasAuthority('article:add')")
    public ResponseEntity zanCun(Article article) {

        //清空审核结果
        article.setAuditState(null);
        //清空修改时间
        article.setEditTime(null);

        //情况一  新增的时候点击暂存  添加文章
        if (("".equals(article.getNo()) || article.getNo() == null) && article.getArticleState() == null) {
            article.setArticleState(0);
            boolean save = articleService.save(article);

            Article addArticle = articleService.getById(article.getNo());

            return ResponseEntity.ok(ApiResult.ok(addArticle));
            //情况二  文章状态 为 发布状态  点击暂存按钮
        } else if (article.getNo() != null && article.getArticleState() == 1) {

            article.setArticleState(0);
            article.setEditNo(String.valueOf(article.getNo()));
            article.setNo(null);

            boolean save = articleService.save(article);

            Article updateArticle = articleService.getById(article.getNo());

            return ResponseEntity.ok(ApiResult.ok(updateArticle));

            //情况三  文章状态 为 暂存状态  点击暂存按钮
        } else if (article.getNo() != null && article.getArticleState() == 0) {
            boolean save = articleService.updateById(article);

            Article updateArticle = articleService.getById(article.getNo());

            return ResponseEntity.ok(ApiResult.ok(updateArticle));
        }

        return ResponseEntity.ok(ApiResult.ok(null));
    }


    /**
     * 查询 文章的发布人
     */
    @GetMapping("/getListByAccountName")
    public ResponseEntity getListByAccountName(String accountName) {
        List<ArticleBo> list = articleService.getListByAccount(accountName);
        return ResponseEntity.ok(ApiResult.ok(list));
    }

    /**
     * 查询 文章的来源
     */
    @GetMapping("/getListBySource")
    public ResponseEntity getListBySource(String source) {
        List<ArticleBo> list = articleService.getListBySource(source);
        return ResponseEntity.ok(ApiResult.ok(list));
    }

}
